import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * jdbc编程入门
 */

public class JDBCTest {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // 1. 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 获得连接
            // mysql8.0版本的url后面有一串东西
            String url = "jdbc:mysql://localhost:3306/jdbctest?zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai";
            String user = "root";
            String password = "root";
            con = DriverManager.getConnection(url, user, password);
            // 3. 基本操作
            // 3.2编写sql语句
            String sql = "select * from user";
            // 3.1获得执行sql语句的对象
            pstmt = con.prepareStatement(sql);

            // 3.3执行sql结果集
            rs = pstmt.executeQuery();
            // 3.4遍历结果集
            while (rs.next()) {
                System.out.print(rs.getInt("id"));
                System.out.print(rs.getString("username"));
                System.out.print(rs.getString("password"));
                System.out.print(rs.getInt("age"));
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 4. 释放资源
            // rs.close();
            // pstmt.close();
            // con.close();

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                rs = null;
            }

            if(pstmt != null){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                pstmt = null;
            }

            if(con != null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                con = null;
            }
        }
        
        
    }
}